package com.darrenchan.leetcode;

/**
 * @Desc
 * @Author chenchi03
 * @CreateTime 2020-02-24 21:05
 */
public class Q114II {
    public void flatten(TreeNode root) {
        helper(root);
    }

    private TreeNode helper (TreeNode root) {
        if(root == null) {
            return null;
        }

        TreeNode leftlast = helper(root.left);
        TreeNode rightlast = helper(root.right);

        if(leftlast != null) {
            leftlast.right = root.right;
            root.right = root.left;
            root.left = null;
        }

        if(rightlast != null) {
            return rightlast;
        }

        if(leftlast != null) {
            return leftlast;
        }

        return root;
    }

}
